package com.biallen.datastructure.sparsesrray;


/**
 * 稀疏算法
 */
public class SparseArray {

    public static void main(String[] args) {
        //创建二维数组
        int[][] arr = new int[11][11];
        arr[0][2] = 8;
        arr[1][2] = 1;
        arr[2][3] = 2;
        arr[5][6] = 7;
        //打印原始数组
        int sumEffect = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                //计算有效数组个数
                if (arr[i][j] != 0) {
                    sumEffect++;
                }
                System.out.printf("%d\t", arr[i][j]);
            }
            System.out.println();
        }
        //原始数组转稀疏数组
        int[][] sparseArr = new int[sumEffect + 1][3];
        sparseArr[0][0] = 11;
        sparseArr[0][1] = 11;
        sparseArr[0][2] = sumEffect;
        int count = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                if (arr[i][j] != 0) {
                    count++;
                    sparseArr[count][0] = i;//记录行编号
                    sparseArr[count][1] = j;//记录列编号
                    sparseArr[count][2] = arr[i][j];//记录编号值
                }
            }

        }
        //打印原稀疏数组
        for (int i = 0; i < sparseArr.length; i++) {
            System.out.printf("%d\t%d\t%d\t\n", sparseArr[i][0], sparseArr[i][1], sparseArr[i][2]);
        }
        ///稀疏数组转原始数组
        int[][] data = new int[sparseArr[0][0]][sparseArr[0][1]];
        for (int i = 1; i < sparseArr.length; i++) {
            data[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
        }
        System.out.println("打印转换后的数组----------------->");
        //打印原始数组
        for (int i = 0; i < data.length; i++) {
            for (int j = 0; j < data[i].length; j++) {
                System.out.printf("%d\t", data[i][j]);
            }
            System.out.println();
        }
    }
}
